package cn.example.demo.config;

import cn.example.demo.exception.APIException;
import cn.example.demo.exception.ResultCode;
import cn.example.demo.vo.ResultVO;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @ProjectName: springbootmybatisinvoicings
 * @Package: cn.example.demo.config
 * @ClassName: ExceptionControllerAdvice
 * @Author: liang
 * @Description: 全局配置错误拦截
 * @Date: 2020/4/11 9:53
 * @Version: 1.0
 */
@RestControllerAdvice
public class ExceptionControllerAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO<String> MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        // 然后提取错误提示信息进行返回
      return new ResultVO<>(ResultCode.FAILED, objectError.getDefaultMessage());
}
    @ExceptionHandler(APIException.class)
    public ResultVO<String> APIExceptionHandler(APIException e) {
        return new ResultVO<>(ResultCode.VALIDATE_FAILED, e.getMsg());
    }
}
